import { unref, ref, watch, onMounted } from "vue";
export function unrefElement(elRef) {
  const plain = unref(elRef);
  return plain?.$el ?? plain;
}

const resetError = (el) => {
  console.log('ssss', el);
  el.className = el.className.replace("err_class", "").trim();
  if (el.parentNode) {
    const ErrorNode = el.parentNode.querySelector(".err_message");
    if (ErrorNode) {
      el.parentNode.removeChild(ErrorNode);
    }
  }
};
const validateError = (el, errorMsg) => {
  if (Array.prototype.includes.call(el.classList, "err_class")) {
    //如果当前组件里已经有了错误提示信息，什么也不做
    return;
  } else {
    const errorNode = document.createElement("p");
    errorNode.className = "err_message";
    errorNode.textContent = errorMsg;
    if (el.parentNode) {
      // 在当前input 元素后追加一个p元素，内容为错误提示
      el.parentNode.appendChild(errorNode);
    }
    // 在当前input 元素上添加一个err_class类名
    el.className += " err_class";
  }
};
export default function useValidate(target, callback, rules) {
  const isPass = ref(true);
  const blur = (e) => {
    const el = unrefElement(target);
    resetError(el);
    isPass.value = true;
    const val = el.value;
    if (rules["max"] && val.length > rules["max"]) {
      isPass.value = false;
      validateError(el, `长度不能超过${rules["max"]}`);
    } else if (rules["required"] && val.length <= 0) {
      isPass.value = false;
      validateError(el, `不能为空`);
    }
  };
  console.log('----', callback);
  const validate = () => {
    var ev = new Event("blur", { bubbles: true, cancelable: true });
    const el = unrefElement(target);
    el.dispatchEvent(ev);
    isPass.value ? callback.success('成功') : callback.fail('失败')
    return isPass;
  };
  onMounted(() => {
    const el = unrefElement(target);
    el.addEventListener("blur", blur);
  });
  return {
    isPass,
    validate,
    resetError
  };
}
